require File.expand_path(File.dirname(__FILE__) + '/util')
require File.expand_path(File.dirname(__FILE__) + '/../config')

class Downloader
  def download_idea force = false
    download(last_build_download_urls[0], force)
  end

  def download_idea_dev force = false
    download(last_build_download_urls[1], force)
  end

  private

  def download url, force = false
    filename = DOWNLOAD_PATH + "/" + url.gsub(/.+\//, '')
    if File.exists? filename then
      puts "#{url} is already downloaded"
      return unless force
      puts "download is forced"
      `rm #{filename}`
    end

    notify_of("downloading #{url}...") do
      Dir.chdir(DOWNLOAD_PATH){ `wget #{url}` }
    end
  end

  def last_build_download_urls
    return @urls unless @urls.nil?

    require 'net/http'
    require 'uri'

    download_url = nil
    eap_page = nil

    notify_of("checking latest EAP build") do
      url = URI.parse("http://www.jetbrains.net" + EAP_URL)
      eap_page = Net::HTTP.start(url.host, url.port) do |http|
        http.get(EAP_URL)
      end
    end

    download_pattern = /.*(http\:\/\/download\.jetbrains\.com\/idea\/idea.+\.tar\.gz)".*/m
    download_url = download_pattern.match(eap_page.body)[1]
    dev_download_pattern = /.*(http\:\/\/download\.jetbrains\.com\/idea\/idea.+dev\.zip)".*/m
    dev_download_url = dev_download_pattern.match(eap_page.body)[1]
    puts "   found #{download_url}"
    puts "   found #{dev_download_url}"

    return (@urls = download_url, dev_download_url)
  end
end